package com.fenghongzhang.day014;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private Intent intent;
    private MyService.MyBinder binder;
    private ServiceConnection serviceConnection;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void start(View view) {
        //启动一个服务
        intent = new Intent(this, MyService.class);
        startService(intent);
    }

    public void stop(View view) {
        //停止一个服务

        stopService(intent);
    }

    public void bind(View view) {
        intent = new Intent(this, MyService.class);
        //和服务建立链接的对象
         serviceConnection = new ServiceConnection() {
            //和服务建立联系时调用
            /**
             * @param name
             * @param service  new Mybinder();
             */
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                binder = (MyService.MyBinder) service;
//                binder.callShow();
            }
            //断开连接时调用
            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        //1, 要启动的服务的intent
        //2, 服务连接对象. (调用服务中的方法,就需要这个对象)
        //3, 绑定的时候后,自动创建服务.
        bindService(intent,serviceConnection,BIND_AUTO_CREATE);

    }

    public void unbind(View view) {
        unbindService(serviceConnection);
    }

    public void show2(View view) {
        binder.callShow2();
    }
}
